<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="商户ID" prop="merchantId">
                            <el-input v-model="condition.search.merchantId" placeholder="商户ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="门店名称" prop="name">
                            <el-input v-model="condition.search.name" placeholder="门店名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="门店地址" prop="address">
                            <el-input v-model="condition.search.address" placeholder="门店地址"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="联系电话" prop="contactPhone">
                            <el-input v-model="condition.search.contactPhone" placeholder="联系电话"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="门店分类" prop="category">
                            <el-select v-model="condition.search.category"
                                       placeholder="门店分类">
                                <el-option
                                    v-for="item in shop_categories"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="城市" prop="city">
                            <el-input v-model="condition.search.city" placeholder="城市"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" @click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="showAddDialog">新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="exportExcel">导出</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            id="mainTable"
            size="small"
            :data="tableData"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="50">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="name"
                width="100px"
                label="门店名称">
                <template v-slot="scope">
                    <el-link @click="onDetail(scope.row)">{{ scope.row.name }}</el-link>
                </template>
            </el-table-column>
            <el-table-column
                prop="category"
                label="门店分类">
            </el-table-column>
            <el-table-column
                prop="city"
                label="城市">
            </el-table-column>
            <el-table-column
                prop="contactPhone"
                label="联系电话">
            </el-table-column>
            <el-table-column
                prop="labels"
                width="100px"
                label="标签">
                <template v-slot="scope">
                    <table-popover :text=scope.row.labels :length="12"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="longitude"
                width="60px"
                label="经度">
            </el-table-column>
            <el-table-column
                prop="latitude"
                width="60px"
                label="纬度">
            </el-table-column>
            <el-table-column
                prop="logo"
                label="LOGO">
                <template v-slot="scope">
                    <el-image v-if="scope.row.logo"
                              style="width: 40px; height: 40px"
                              :src="scope.row.logo"
                              :preview-src-list="logoUrls"
                              fit="fill">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column
                prop="managerQrcode"
                label="店长二维码">
                <template v-slot="scope">
                    <el-image v-if="scope.row.managerQrcode"
                              style="width: 40px; height: 40px"
                              :src="scope.row.managerQrcode"
                              fit="fill">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column
                prop="operateTime"
                label="营业时间">
            </el-table-column>
            <el-table-column
                prop="dpShopUuid"
                width="90px"
                label="点评UUID">
                <template v-slot="scope">
                    <el-link @click="clickUuid(scope.row)">{{ scope.row.dpShopUuid }}</el-link>
                </template>
            </el-table-column>
            <el-table-column
                prop="address"
                width="100px"
                label="门店地址">
                <template v-slot="scope">
                    <table-popover :text=scope.row.address :length="16"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="route"
                width="100px"
                label="到达路线">
                <template v-slot="scope">
                    <table-popover :text=scope.row.route :length="16"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="parking"
                width="100px"
                label="停车信息">
                <template v-slot="scope">
                    <table-popover :text=scope.row.parking :length="16"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="createTime"
                width="90px"
                label="创建时间">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                width="90px"
                label="更新时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="120px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                        <el-button @click="onDetail(scope.row)" type="text" size="small">详情</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-drawer direction="rtl" :title=addOrUpdateDialogTitle width="30%"
                   :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" size="small">
                <el-form-item>
                    <el-button @click="openMap" type="success" size="mini">打开地图选址</el-button>
                </el-form-item>
                <el-form-item label="门店名称">
                    <el-input v-model="addOrUpdateForm.name" placeholder="门店名称"></el-input>
                </el-form-item>
                <el-form-item label="门店地址">
                    <el-input v-model="addOrUpdateForm.address" placeholder="门店地址" type="textarea"
                              autosize></el-input>
                </el-form-item>
                <el-form-item label="门店分类">
                    <el-select v-model="addOrUpdateForm.category"
                               placeholder="门店分类">
                        <el-option
                            v-for="item in shop_categories"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="城市">
                    <el-input v-model="addOrUpdateForm.city" placeholder="城市" disabled></el-input>
                </el-form-item>
                <el-form-item label="联系电话">
                    <el-input v-model="addOrUpdateForm.contactPhone" placeholder="联系电话"></el-input>
                </el-form-item>
                <el-form-item label="标签">
                    <el-select v-model="addOrUpdateForm.labels"
                               multiple
                               clearable
                               filterable
                               allow-create
                               placeholder="门店标签">
                        <el-option
                            v-for="item in shopLabels"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="经度">
                    <el-input v-model="addOrUpdateForm.longitude" placeholder="经度" disabled></el-input>
                </el-form-item>
                <el-form-item label="纬度">
                    <el-input v-model="addOrUpdateForm.latitude" placeholder="纬度" disabled></el-input>
                </el-form-item>
                <el-form-item label="营业时间">
                    <el-input v-model="addOrUpdateForm.operateTime" type="textarea" autosize
                              placeholder="营业时间"></el-input>
                </el-form-item>
                <el-form-item label="到达路线">
                    <el-input v-model="addOrUpdateForm.route" type="textarea" autosize
                              placeholder="到达路线"></el-input>
                </el-form-item>
                <el-form-item label="停车信息">
                    <el-input v-model="addOrUpdateForm.parking" type="textarea" autosize
                              placeholder="停车信息"></el-input>
                </el-form-item>
                <el-form-item label="短信签名">
                    <el-input v-model="addOrUpdateForm.smsSign" placeholder="短信签名"></el-input>
                </el-form-item>
                <el-form-item label="点评门店UUID">
                    <el-input v-model="addOrUpdateForm.dpShopUuid" placeholder="点评门店UUID"></el-input>
                </el-form-item>
                <el-form-item label="店长二维码">
                    <el-input v-model="addOrUpdateForm.managerQrcode" type="textarea" autosize
                              placeholder="店长二维码"></el-input>
                </el-form-item>
                <el-form-item label="门店LOGO">
                    <el-upload
                        ref="upload"
                        action=""
                        list-type="picture"
                        :multiple="false"
                        :limit="1"
                        :auto-upload="false"
                        accept="image/png,image/jpg,image/jpeg"
                        :show-file-list="true"
                        :before-remove="beforeRemove"
                        :on-exceed="handleExceed"
                        :http-request="handleRequest">
                        <el-button size="mini" type="success">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            只能上传图片文件格式。<br/>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div class="drawer-footer">
                <el-button class="drawer-footer-button" @click="addOrUpdateDialogVisible = false" size="small">取 消
                </el-button>
                <el-button class="drawer-footer-button" @click="addOrUpdateConfirm" type="primary" size="small">确 定
                </el-button>
            </div>
            <el-dialog :visible.sync="mapShow" append-to-body>
                <iframe id="mapPage" width="100%" height="500px" frameborder=0
                        src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=DD2BZ-JIMC4-OICUR-XJ2AV-RFXUT-K2FRS&referer=myapp">
                </iframe>
            </el-dialog>
        </el-drawer>
    </div>
</template>

<script>
import {addShop, deleteShop, getDpShopByShopUuid, getParamValue, getShopByPage, updateShop} from '@/api/api'
import TablePopover from "@/component/single/TablePopover";

export default {
    name: "Shop",
    components: {TablePopover},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 50,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},
            // 地图默认不显示
            mapShow: false,
            // logo数组
            logoUrls: [],

            // 门店分类
            shop_categories: [],
            // 门店标签
            shopLabels: this.CONST.shop_labels,
        }
    },
    watch: {
        $route: function (newVal, oldVal) {
            let page = newVal.query.page;
            if (page) {
                this.condition.page = Number(page);
            }
            let rows = newVal.query.rows;
            if (rows) {
                this.condition.rows = Number(rows);
            }
            this.getData();
        }
    },
    methods: {
        clickUuid(row) {
            if (row.dpShopUuid) {
                getDpShopByShopUuid({"shopUuid": row.dpShopUuid}).then(data => {
                    if (data.respCode == 1000) {
                        if (data.body) {
                            this.$router.push({path: '/dp/shop/detail', query: {shopId: data.body.shopId}});
                        } else {
                            this.$message({
                                type: 'error',
                                message: '暂时找不到该门店，可能已经被管理员删除!'
                            });
                        }
                    }
                })
            }
        },
        handleRequest(file) {
            // 手动上传，把文件对象赋值给表单里面的对象
            this.addOrUpdateForm.file = file.file;
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            let queryParams = {page: this.condition.page, rows: this.condition.rows};
            this.$router.push({query: queryParams});
        },
        handleCurrentChange(val) {
            let queryParams = {page: this.condition.page, rows: this.condition.rows};
            this.$router.push({query: queryParams});
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles();
            }
            this.$set(this.addOrUpdateForm, "operateTime", '11:00-13:30,17:00-22:00')
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
            this.addOrUpdateForm.labels = row.labels.split(",");
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        add: function () {
            // 一定要先手动触发上传
            this.$refs.upload.submit();
            // 判断图片格式
            if (!this.GLOBAL.isImage(this.addOrUpdateForm.file, this)) {
                return;
            }
            // 一定要变成formData格式，后端不能用@RequestBody接收
            let formData = new FormData();
            Object.keys(this.addOrUpdateForm).forEach((key) => {
                formData.append(key, this.addOrUpdateForm[key]);
            });
            addShop(formData).then(data => {
                if (data.respCode == 1000) {
                    this.$message({
                        type: 'success',
                        message: '新增成功!'
                    });
                    this.addOrUpdateDialogVisible = false;
                    // 清空文件列表
                    this.$refs.upload.clearFiles();
                    this.getData();
                }
            });
        },
        update: function () {
            // 一定要先手动触发上传
            this.$refs.upload.submit();
            if (this.addOrUpdateForm.file) {
                // 判断图片格式
                if (!this.GLOBAL.isImage(this.addOrUpdateForm.file)) {
                    return;
                }
            }
            // 一定要变成formData格式，后端不能用@RequestBody接收
            let formData = new FormData();
            Object.keys(this.addOrUpdateForm).forEach((key) => {
                formData.append(key, this.addOrUpdateForm[key]);
            });
            updateShop(formData).then(data => {
                if (data.respCode == 1000) {
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        onDetail: function (row) {
            this.$router.push({path: '/merchant/shop/detail', query: {id: row.id}});
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteShop({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        openMap: function () {
            this.mapShow = true;
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            getShopByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                this.tableData.forEach((item, index, arr) => {
                    this.logoUrls.push(item.logo);
                })
            });
            this.getShopCategories();
        },
        // 获取门店分类
        getShopCategories() {
            this.shop_categories = [];
            getParamValue('food_shop_category').then(data => {
                let ss = data.body;
                if (ss) {
                    let tt = ss.split(",");
                    tt.forEach((item, index, arr) => {
                        this.shop_categories.push(
                            {
                                value: item,
                                label: item,
                            }
                        )
                    })
                }
            })
        }
    },
    created() {
        let page = this.$route.query.page;
        if (page) {
            this.condition.page = Number(page);
        }
        let rows = this.$route.query.rows;
        if (rows) {
            this.condition.rows = Number(rows);
        }
        this.getData();
    },
    mounted() {
        let that = this
        window.addEventListener('message', function (event) {
            // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
            let loc = event.data;
            // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
            if (loc && loc.module == 'locationPicker') {
                console.log('location', loc);
                that.mapShow = false;
                that.$set(that.addOrUpdateForm, "name", loc.poiname)
                that.$set(that.addOrUpdateForm, "address", loc.poiaddress)
                that.$set(that.addOrUpdateForm, "city", loc.cityname)
                that.$set(that.addOrUpdateForm, "longitude", loc.latlng.lng)
                that.$set(that.addOrUpdateForm, "latitude", loc.latlng.lat)
            }
        }, false);
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
